package io.polly.ldz.filter;

import io.polly.ldz.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author ldz112@163.com
 * @Classname JwtInterceptor
 * @Version V1.0
 * @Description TODO
 * @Date 2025/5/28 11:17
 * Copyright (C) 2023 All Rights Reserved
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authHeader= request.getHeader(tokenHeader);
        // 去除字段名称, 获取真正token
        String authToken = authHeader.substring(tokenHead.length());
        try{
            request.setAttribute("userName", jwtTokenUtil.getUserNameFromToken(authToken));
            return true;
        }catch (Exception e){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        return false;

    }
}
